package logic

import (
	"context"
	"develop/model/cache"
	"develop/model/mysql"
	"errors"
	"fmt"

	"math/rand"

	"develop/usersrpc/internal/svc"
	"develop/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *usersrpc.RegisterRequest) (*usersrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var findPhoneId mysql.User_info
	err := findPhoneId.FindPhoneId(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, err
	}

	if findPhoneId.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}
	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.PhoneNum).Result()
	if result != in.SendSmsCode {
		return nil, errors.New("短信验证码不正确")
	}
	info := &mysql.User_info{
		Phone_Num:   in.PhoneNum,
		Pwd:         in.Pwd,
		Nick_Name:   fmt.Sprintf("用户%d", rand.Intn(1000000)),
		Avatar_Link: "www.baidu.com",
	}
	err = info.UserCreate(mysql.DB)
	if err != nil {
		return nil, err
	}
	return &usersrpc.RegisterResponse{
		UserId: int64(info.ID),
	}, nil
}
